using System;
using System.Xml;

namespace Mbs.CastleContainer
{
    class ChooseElementProcessor : AbstractStatementElementProcessor
    {
        private static readonly String WhenElemName = "when";
        private static readonly String OtherwiseElemName = "otherwise";

        public ChooseElementProcessor()
        {
        }

        public override String Name
        {
            get { return "choose"; }
        }

        public override void Process(IXmlProcessorNodeList nodeList, IXmlProcessorEngine engine)
        {
            XmlElement element = nodeList.Current as XmlElement;

            XmlDocumentFragment fragment = CreateFragment(element);

            foreach (XmlNode child in element.ChildNodes)
            {
                if (IgnoreNode(child)) continue;

                XmlElement elem = GetNodeAsElement(element, child);

                bool found = false;

                if (elem.Name == WhenElemName)
                {
                    found = ProcessStatement(elem, engine);
                }
                else if (elem.Name == OtherwiseElemName)
                {
                    found = true;
                }
                else
                {
                    throw new XmlProcessorException("'{0} can not contain only 'when' and 'otherwise' elements found '{1}'", element.Name, elem.Name);
                }

                if (found)
                {
                    if (elem.ChildNodes.Count > 0)
                    {
                        MoveChildNodes(fragment, elem);
                        engine.DispatchProcessAll(new DefaultXmlProcessorNodeList(fragment.ChildNodes));
                    }
                    break;
                }
            }

            ReplaceItself(fragment, element);
        }
    }
}
